package com.javademo.multithreadingtest;

import lombok.extern.slf4j.Slf4j;

import java.util.LinkedList;
import java.util.List;
import java.util.Queue;

@Slf4j
public class WaitAndNotifyTest {
    public static void main(String[] args) {
        TaskQueue1 taskQueue = new TaskQueue1();
        List<Thread> ts = new LinkedList<>();
        for (int i = 0; i < 5; i++){
            Thread t = new Thread(() -> {
                while (true){
                    String task = null;
                    try {
                        task = taskQueue.getTask();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    log.info("正在执行任务：" + task);
                }
            });
            t.start();
            ts.add(t);
        }
        log.info("ts线程列表：{}", ts);
        Thread add = new Thread(() -> {
            for (int i = 0; i < 10; i++){
                String task = "task-" + i;
                log.info("添加任务：" + task);
                try {
                    taskQueue.addTask(task);
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                try {
                    Thread.sleep(100);
                }catch (InterruptedException e){
                    log.error("线程中断2：{}", e.getMessage(), e);
                }
            }
        });
        add.start();
        try {
            add.join();
            Thread .sleep(100);
        }catch (InterruptedException e){
            log.error("线程中断3：{}", e.getMessage(), e);
        }
        for (Thread t : ts){
            t.interrupt();
        }
    }
}

@Slf4j
class TaskQueue{
    Queue<String> queue = new LinkedList<>();

    public synchronized void addTask(String task){
        this.queue.add(task);
        this.notifyAll();
    }

    public synchronized String getTask() {
        int count = 0;
        while (queue.isEmpty()){
            log.info("队列为空，{}等待中...{}次", Thread.currentThread().getName(), count++);
            try {
                this.wait();
                Thread.sleep(1000);
            }catch (InterruptedException e){
                log.error("线程中断4：{}", e.getMessage(), e);
            }

        }
        log.info("队列不为空，{}开始执行任务", Thread.currentThread().getName());
        return queue.remove();
    }
}